<template>
  <div>
    <div style="margin-bottom: 15px">
      <el-input v-model="beginTime" style="width: 200px" placeholder="请输入开始时间"></el-input>
      <el-input v-model="endTime" style="width: 200px" placeholder="请输入结束时间"></el-input>
      <el-button type="primary" icon="el-icon-search" style="margin-left: 10px"
                 @click="findHealthByUserIdAndTimeRange"></el-button>
      <el-button type="warning" icon="el-icon-refresh-right" style="margin-left: 10px" @click="reset"></el-button>
      <el-button type="success" @click="processHealthRecordStart">开启健康信息记录</el-button>
      <el-button type="danger" @click="processHealthRecordStop">关闭健康信息记录</el-button>
    </div>

    <div class="container" style="padding:0 0;">
      <div ref="chart_1" style="width: 50%; height: 500px; background-color:rgba(10, 2, 39, 0.796);"></div>
      <div ref="chart_2" style="width: 50%; height: 500px; background-color:rgba(10, 2, 39, 0.796);"></div>
    </div>
    <div>
    </div>

    <!--用户信息表-->
    <div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="healthId" label="id"></el-table-column>
        <el-table-column prop="userId" label="用户名"></el-table-column>
        <el-table-column prop="heartRate" label="心率"></el-table-column>
        <el-table-column prop="bloodPressureSystolic" label="收缩压"></el-table-column>
        <el-table-column prop="bloodPressureRelease" label="舒张压"></el-table-column>
        <el-table-column prop="time" label="时间"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>

import * as echarts from 'echarts';
import request from "@/utils/request";
import {Client} from '@stomp/stompjs';
import SockJS from 'sockjs-client';

export default {
  name: 'healthChart',
  data() {
    return {
      user: sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {},
      tableData: [],
      beginTime: '',
      endTime: '',
      chart_1: null,
      chart_2: null,
      stompClient: null,
    }
  },
  created() {

  },
  mounted() {
    this.fetchData();
    this.chart_1 = echarts.init(this.$refs.chart_1);
    this.chart_2 = echarts.init(this.$refs.chart_2);
    this.initChart();
    this.connect();
    // this.chart_1.setOption({
    //   xAxis: {
    //     type: 'time',
    //     data: this.tableData.map(item => item.time)
    //   },
    //   yAxis: {},
    //   series: [{
    //     data: this.tableData.map(item => ({
    //       value: [item.time, item.heartRate],
    //       name: item.time
    //     }))
    //   }]
    // });
  },
  methods: {
    async fetchData() {
      try {
        await fetch("http://localhost:6174/health/search/" + this.user.id).then(response => {
          return response.json();
        }).then(data => {
          if (data.code === '0') {
            this.tableData = data.data
            this.$message.success("获取健康信息成功")
          }
        })
      } catch (error) {
        console.error('There was a problem with your fetch operation:', error);
      }
    },
    //清空
    reset() {
      request.delete('/health/delete/' + this.user.id).then(res => {
        if (res.code === '0') {
          this.$message.success("清空健康信息成功")
          this.tableData = []

          this.initChart()
        } else {
          this.$message.error("清空健康信息失败")
        }
      }).catch(error => {
        console.error('Error resetting data:', error);
      })
    },
    findHealthByUserIdAndTimeRange() {
      if (this.beginTime === '' || this.endTime === '') {
        this.fetchData();
        return;
      }
      request.get("/health/search/timeRange/" + this.user.id, {
        params: {
          beginTime: this.beginTime,
          endTime: this.endTime
        }
      }).then(res => {
        if (res.code === '0') {
          this.processHealthRecordStop();
          this.tableData = res.data;
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    processHealthRecordStart() {
      request.post("/process/start/healthRecord/" + this.user.id).then(res => {
        if (res.code === '0') {
          this.$message.success("开启成功");
          if (this.stompClient && this.stompClient.connected) {
            this.stompClient.publish({
              destination: '/app/startHealthPushing',
              body: `${this.user.id}` // 将用户ID作为消息体发送
            });
            console.log("已开始推送");
          }
        } else {
          this.$message.error(res.msg)
        }
      }).catch(error => {
        console.error('Error starting process:', error);
      })
    },
    processHealthRecordStop() {
      request.post("/process/stop/healthRecord/" + this.user.id).then(res => {
        if (res.code === '0') {
          this.$message.success("关闭成功");
          if (this.stompClient && this.stompClient.connected) {
            this.stompClient.publish({
              destination: '/app/stopHealthPushing',
              body: `${this.user.id}` // 将用户ID作为消息体发送
            });
            console.log("已结束推送");
          }
        } else {
          this.$message.error(res.msg)
        }
      }).catch(error => {
        console.error('Error stopping process:', error);
      })
    },
    initChart() {
      this.initChart_1()
      this.initChart_2()
    },
    initChart_1() {
      const xAxisData = this.tableData.map(item => item.time);
      const heartRateData = this.tableData.map(item => ({
        value: [item.time, item.heartRate],
        name: item.time
      }));
      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: "#dddc6b",
            },
          },
        },
        title: {
          text: "心率",
          left: "left",
          textStyle: {
            color: "rgba(11, 240, 125, 0.796)",
            fontSize: "15",
          },
        },
        grid: {
          left: "5%",
          top: "10%",
          right: "5%",
          bottom: "5%",
          containLabel: true,
        },
        xAxis: {
          type: 'time',
          data: xAxisData,
          boundaryGap: false,
          axisLabel: {
            textStyle: {
              color: "rgba(255,255,255,.5)",
              fontSize: 10,
            },
          },
          axisLine: {
            lineStyle: {
              color: "rgba(255,255,255,.2)",
            },
          },
          splitLine: {
            lineStyle: {
              color: "rgba(255,255,255,.1)",
            },
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '心率',
            min: 0,
            max: 200,
            axisTick: {show: false},
            axisLabel: {
              textStyle: {
                color: "rgba(255,255,255,.5)",
                fontSize: 10,
              },
              // formatter: '{value} KM',
            },
            axisLine: {
              lineStyle: {
                color: "rgba(255,255,255,.1)",
              },
            },
            splitLine: {
              lineStyle: {
                color: "rgba(255,255,255,.1)",
              },
            },
          },
        ],
        series: [
          {
            name: '心率',
            type: 'line',
            data: heartRateData,
            yAxisIndex: 0,

            // 平滑曲线 或 折线
            // smooth: true,
            // 面接图
            areaStyle: {},
            symbol: "circle",
            symbolSize: 5,
            lineStyle: {
              normal: {
                // color: '#0184d5',
                width: 2,
              },
            },
          }
        ]
      };
      this.chart_1.setOption(option);
    },
    initChart_2() {
      const xAxisData = this.tableData.map(item => item.time);
      const bloodPressureSystolicData = this.tableData.map(item => ({
        value: [item.time, item.bloodPressureSystolic],
        name: item.time
      }));
      const bloodPressureRelease = this.tableData.map(item => ({
        value: [item.time, item.bloodPressureRelease],
        name: item.time
      }));

      var option = {
        title: {
          text: "血压",
          left: "left",
          textStyle: {
            color: "rgba(11, 240, 125, 0.796)",
            fontSize: "15",
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            lineStyle: {
              color: "#dddc6b",
            },
          },
        },
        grid: {
          left: "5%",
          top: "10%",
          right: "5%",
          bottom: "5%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "time",
            data: xAxisData,
            boundaryGap: false,
            axisLabel: {
              textStyle: {
                color: "rgba(255,255,255,.5)",
                fontSize: 10,
              },
            },
            axisLine: {
              lineStyle: {
                color: "rgba(255,255,255,.2)",
              },
            },
            splitLine: {
              lineStyle: {
                color: "rgba(255,255,255,.1)",
              },
            },
          },
        ],

        yAxis: [
          {
            type: "value",
            name: "mmHg",
            min: 0,
            max: 300,
            axisTick: {show: false},
            axisLabel: {
              textStyle: {
                color: "rgba(255,255,255,.5)",
                fontSize: 10,
              },
              // formatter: '{value} KM',
            },

            axisLine: {
              lineStyle: {
                color: "rgba(255,255,255,.1)",
              },
            },

            splitLine: {
              lineStyle: {
                color: "rgba(255,255,255,.1)",
              },
            },
          },
        ],
        series: [
          {
            name: "收缩压",
            type: "line",
            // 平滑曲线 或 折线
            smooth: true,
            // 面接图
            // areaStyle: {},
            symbol: "circle",
            symbolSize: 5,
            lineStyle: {
              normal: {
                // color: '#0184d5',
                width: 2,
              },
            },
            data: bloodPressureSystolicData,
          },
          {
            name: "舒张压",
            type: "line",
            smooth: true,
            symbol: "circle",
            symbolSize: 5,
            lineStyle: {
              normal: {
                // color: '#0184d5',
                width: 2,
              },
            },
            data: bloodPressureRelease,
          },
        ],
      };
      this.chart_2.setOption(option);
    },
    connect() {
      const socket = new SockJS('http://localhost:6174/ws');
      this.stompClient = new Client({
        webSocketFactory: () => socket,
        onConnect: () => {
          console.log('WebSocket connected');
          this.stompClient.subscribe(`/topic/pushHealth/${this.user.id}`, message => {
            const healthData = JSON.parse(message.body);
            this.tableData = healthData; // 更新数据展示
            console.log('Received health data:', healthData);
          });
        },
        onStompError: (frame) => {
          console.error('Broker error: ' + frame.headers['message']);
          console.error('Details: ' + frame.body);
        }
      });
      this.stompClient.activate();
    }
  },
  watch: {
    tableData(newValue, oldValue) {
      console.log(newValue)
      this.initChart();
    }

    // tableData: {
    //   deep: true,
    //   handler(newVal) {
    //     if (Array.isArray(newVal)) {
    //       if (this.chart_1) {
    //         this.chart_1.setOption({
    //           xAxis: {
    //             data: newVal.map(item => item.time)
    //           },
    //           yAxis: {},
    //           series: [{
    //             data: newVal.map(item => ({
    //               value: [item.time, item.heartRate],
    //               name: item.time
    //             }))
    //           }]
    //         });
    //       }
    //     }
    //   }
    // }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 20px;
}

.left-panel, .right-panel {
  width: 45%; /* 根据需要调整 */
  text-align: center;
  border: 1px solid #ccc; /* 可选，仅为了更清晰地看到边界 */
  padding: 20px;
  box-sizing: border-box;
}
</style>
